<?php
/**
 * smartyの修飾詞プラグイン
 * {$nanntyara|関数名}でsmartyから修飾詞として関数呼べる
 *
 * @author tanaka
 * @package View_Smarty_Plugin
 * @subpackage Modifier
 */
final class View_Smarty_Plugin_Modifier extends Base_Singleton
{
	/**
	 * 日付フォーマット
	 * {$val|dateformat:$format}
	 *
	 * @param mixed $val
	 * @return val
	 */
	public function dateformat($val, $format = "Y/m/d")
	{
		// Datetimeオブジェクト
		if ($val instanceof DateTime) {
			return $val->format($format);
		}

		// 配列
		if (is_array($val)) {
			foreach ($val as $key => $value) {
				$val[$key] = $this->dateformat($value);
			}
			return $val;
		}

		// 文字列 柔軟だけど遅い気がする・・・
		if (is_string($val)) {

			if (preg_match('/^(\d{4})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})/', $val)) {
				$Y = preg_replace('/^(\d{4})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})/', '$1', $val);
				$m = preg_replace('/^(\d{4})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})/', '$2', $val);
				$d = preg_replace('/^(\d{4})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})/', '$3', $val);
				$H = preg_replace('/^(\d{4})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})/', '$4', $val);
				$i = preg_replace('/^(\d{4})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})/', '$5', $val);
				$s = preg_replace('/^(\d{4})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})\D(\d{1,2})/', '$6', $val);
				return date($format, mktime($H, $i, $s, $m, $d, $Y));
			}
		}

		// タイムスタンプ型
		if (preg_match('/^\d+$/', $val)) {
			
			return date($format, $val);
		}

		return $val;
	}

	/**
	 * 空文字だった場合代わりの文字を出力
	 * デフォルトは&nbsp;
	 * エスケープ処理後に使用すること
	 *
	 * @param string $val
	 * @param string optional $untiStr
	 * @return string
	 */
	public function unti_empty($val, $untiStr = '&nbsp;')
	{
		if (strlen(trim($val))) {
			return $val;
		}

		return $untiStr;
	}
	
	/**
	 * 一定バイトごとにソフトハイフンを挿入します。
	 * 
	 * @param string $val
	 * @param int optional $perBytes
	 * @return string
	 */
	public function soft_hyphen($val, $perBytes = 4)
	{
		$val = mb_fold($val, $perBytes);
		
		$result = '';
		foreach($val as $str){
			$result .= $str . '&shy;';
		}
		return $result;
	}
}
